﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lib.Web.Mvc.JQuery.JqGrid;
using Stertex.Service;
using Stertex.Repository;
using www.Stertex.com.Models;
using Stertex.Models;
using Stertex.Common.EF;

namespace www.Stertex.com.Controllers
{
    public class SearchController : Controller
    {
        //
        // GET: /Search/

        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetResults(JqGridRequest request, string Firstname, string Lastname)
        {
            ServiceCore<Owner> svc1 = new ServiceCore<Owner>();
            ServiceCore<Profile> svc = new ServiceCore<Profile>();
            var profiles = svc.GetPaged(p => (!string.IsNullOrEmpty(Firstname) ? p.Firstname.Contains(Firstname) : true) && (!string.IsNullOrEmpty(Lastname) ? p.Lastname.Contains(Lastname) : true),
                new IOrderByClause<Profile>[] { new OrderByClause<Profile, string>(p => p.Title) },
                request.PageIndex + 1, request.RecordsCount);
            int totalRecordsCount = profiles.TotalItemCount;
            
            JqGridResponse response = new JqGridResponse()
            {
                TotalPagesCount = (int)Math.Ceiling((float)totalRecordsCount / (float)request.RecordsCount),
                PageIndex = request.PageIndex,
                TotalRecordsCount = totalRecordsCount
            };
            response.Records.AddRange(from p in profiles
                                      select new JqGridRecord<ProfileViewModel>(Convert.ToString(p.ProfileID), new ProfileViewModel(p)));

            return new JqGridJsonResult() { Data = response };
        }
    }
}
